#!/usr/bin/env bash
VERSION=2.1.0
profile=default
tests=no
release=no
prefix=NONE
test -e "$CONFIG_SITE" && . "$CONFIG_SITE"
test "$prefix" = NONE && prefix=/usr/local

usage ()
{
	profiles=`ls profiles | sed -e "s/$/,/g" | fmt | sed -e 's/,$//' -e "s/ChangeLog, //"`
	echo ""
	echo "Usage : configure [--prefix=PREFIX] [--select] [--profile=PROFILE] [--release-builds]"
	echo ""
	echo "This script allows selecting and configuring a set of MonoDevelop"
	echo "modules to be included in an integrated build."
	echo ""
	echo "The MonoDevelop build system consists of a 'main' module, which "
	echo "contains the main distribution, and a number of additional add-ins"
	echo "in subdirectories of 'extras'. "
	echo ""
	echo "The 'extras' add-ins are designed to be built and distributed separately,"
	echo "and therefore build against your system-installed MonoDevelop by default."
	echo "However, this script sets them up to build against the MonoDevelop in"
	echo "'main', and ensures that they will be loaded when MonoDevelop is launched"
	echo "with 'make run' in this top-level directory. This is very useful for"
	echo "development and testing."
	echo ""
	echo "The first time the configure script is executed, it will ask you"
	echo "to select the add-ins to be included in the build. Further executions"
	echo "will configure only the selected add-ins. To select a new list of"
	echo "add-ins, run this script using the --select option."
	echo ""
	echo "You can also configure a predefined list of modules by specifying"
	echo "a build profile using the --profile option."
	echo ""
	echo "Options:"
	echo ""
	echo "--prefix=PREFIX"
	echo ""
	echo "  Select the install directory prefix."
	echo ""
	echo "--select"
	echo ""
	echo "  Shows a list of add-ins and allows selecting which ones should be"
	echo "  included in the build. It can be used in combination with --profile"
	echo "  to select the add-ins to be built for a specific profile."
	echo ""
	echo "--enable-tests"
	echo "  Build the md test suite"
	echo ""
	echo "--enable-release"
	echo "  Builds md in release mode"
	echo ""
	echo "--enable-mac32"
	echo "  Build for i386 on OS X"
	echo ""
	echo "--profile=PROFILE"
	echo ""
	echo "  Configure the build system using the provided profile."
	echo "  A 'profile' is a list of 'extras' directories and arguments for their "
	echo "  configure scripts, and arguments for the 'main' configure script. To "
	echo "  add a profile, simply create a file in the 'profiles' directory."
	echo "  The 'default' profile is used when none is specified."
	echo ""
	echo "  Profiles available:" $profiles
	echo ""
}

validate_profile ()
{
	test -z "$1" && return 0
	for c in `ls profiles`; do
		if [ "$c" = "$1" ]; then
			return 1
		fi
	done
	return 0
}

select_packages ()
{
	if [[ ! -a profiles/$profile ]] ; then
		cp profiles/stable profiles/$profile
	fi
	n=1
	for p in `sed -e /#/d -e 's/ /,/g' < profiles/all` ; do
		packages[$n]=$p
		if test x1 == x`grep -c -s $p profiles/$profile`; then
			sel=X
		else
			sel=" "
		fi
		selection[$n]=$sel
		let "n=n+1"
	done
	pcount=$n
	while [[ 1 ]]
	do
		echo Select the packages to include in the build for the profile \'$profile\':
		echo
		n=1
		for p in ${packages[*]} ; do
			echo $n. [${selection[n]}] $p
			let "n=n+1"
		done
		echo
		echo "Enter the number of an add-in to enable/disable,"
		read -a response  -p"(q) quit, (c) clear all, (s) select all, or ENTER to continue:  "
		echo
		if [ -z $response ] ; then
			break
		elif [ $response == q -o $response == Q ] ; then
			exit 1
		elif [ $response == c -o $response == C ] ; then
			for ((n=1; n < pcount; n++))
			do
				selection[$n]=" "
			done
		elif [ $response == s -o $response == S ] ; then
			for ((n=1; n < pcount; n++))
			do
				selection[$n]=X
			done
		elif [ x${selection[response]} = xX ] ; then
			selection[$response]=" "
		else
			selection[$response]=X
		fi
	done
	n=1
	rm -f profiles/$profile
	for p in ${packages[*]} ; do
		if [ x${selection[n]} == xX ]; then
			echo ${packages[n]} >> profiles/$profile
		fi
		let "n=n+1"
	done
}

handle_config_error ()
{
	if test `uname` = "Darwin"; then
		echo ""
		echo "Have you followed http://www.monodevelop.com/developers/building-monodevelop/#macosx ?"
		echo ""
	fi
	exit 1
}

configure_packages ()
{
	rm -f local-config/*
	localconf=`pwd`/local-config
	for p in `sed -e /#/d -e 's/ /,/g' < profiles/$profile` ; do
		path=`echo $p | cut -d ',' -f 1`
		ops=`echo $p | sed -e s,$path,, -e 's/,/ /'g`
		if test xyes == x$tests; then
			enable_tests=--enable-tests
		else
			enable_tests=" "
		fi

		if test `uname` != "Darwin" || test xno == x$x64; then
			enable_x64=--with-macarch=i386
		else
			enable_x64=--with-macarch=x86_64
		fi

		prefixarg="--prefix=$prefix"
		builddir=`pwd`/$path/build

		for p in $ops ; do
			arg=`echo $p | cut -d '=' -f 1`
			if [ $arg == "--addins-dir" ] ; then
				builddir=`pwd`/$path/`echo $p | cut -d '=' -f 2`
			fi
			if [ $p == "--no-prefix" ] ; then
				prefixarg=""
			fi
		done
		if test xyes == x$release; then
			ops="$ops --enable-release"
		fi

		title="Configuring package: $path"
		nc=`echo $title | wc -m`
		echo $title
		for ((n=1; n < nc; n++)); do echo -n "-"; done
		echo
		echo "Configuration options: $ops"
		if test -a $path/autogen.sh; then
			sct="./autogen.sh $enable_tests $enable_x64"
		elif test -a $path/configure; then
			sct=./configure
		elif test -a $path/configure.sh; then
			sct=./configure.sh
		else
			echo -en '\033[0;31m'
			echo Configuration script not found in directory: $path
			echo Try running $ git submodule update --init --recursive
			echo -en '\033[0m'
			exit 1
		fi
		pushd $path > /dev/null
		PKG_CONFIG_PATH=$localconf:$PKG_CONFIG_PATH $sct $prefixarg $ops || handle_config_error
		popd > /dev/null
		create_local_config $path $builddir
		packages="$packages $path"
	done
	rm -f local-config/main.addins
	return 0
}

create_local_config ()
{
	# Get the version from the version.config file, if it exists
	if test -a version.config; then
		ver=`grep ^Version version.config|cut -d '=' -f 2|tr -d '\n'`
	else
		ver=VERSION
	fi

	# Copy the .pc file to local-config, and set the base lib directory
	mkdir -p local-config
	builddir=$2
	for f in `ls $1/*.pc.in 2>/dev/null`; do
		pcfile=`echo $f | sed s,.*/,, | sed s/\.in$//`
		sed -e s,libdir=.*,libdir=$builddir, -e s/@VERSION@/$ver/g $f> local-config/$pcfile
	done

	# Generate the .addins file for the package
	addins=local-config/`echo $path | sed s,/,_,g`.addins
	echo "<Addins>" > $addins
	echo "  <Directory include-subdirs=\"true\">$builddir</Directory>" >> $addins
	echo "</Addins>" >> $addins
}

echo

while test x$1 != x; do
	case $1 in
		--enable-tests)
			tests=yes
			;;
		--enable-release)
			release=yes
			;;
		--enable-mac32)
			x64=no
			;;
		--prefix=*)
			prefix=`echo $1 | sed 's/--prefix=//'`
			;;
		--prefix)
			shift
			prefix=$1
			;;
		--select)
			select=yes
			;;
		--profile=*)
			prof=`echo $1 | sed 's/--profile=//'`
			profile=$prof
			;;
		--profile)
			shift
			profile=$1
			;;
		--help)
			usage
			exit
			;;
		*)
			echo Unknown argument $1 >&2
			usage
			exit 1
			;;
	esac
	shift
done

if test `uname` = "Darwin" && test "x$profile" = "xdefault"; then
	profile="mac"
fi

validate_profile "$profile"
if [ ! $? -eq 1 ]; then
	echo "The build profile '$profile' does not exist. A new profile will be created."
fi
if [ x$select == xyes -o ! -a profiles/$profile ]; then
	select_packages
fi

if test `uname` = "Darwin"; then
	# if building on bots or in default environment, fix up paths to use system Mono
	if test "x$BUILD_REVISION" != "x" -o "x$DYLD_FALLBACK_LIBRARY_PATH" = "x"; then
		export DYLD_FALLBACK_LIBRARY_PATH="/Library/Frameworks/Mono.framework/Versions/Current/lib:/lib:/usr/lib"
		export PATH="/Library/Frameworks/Mono.framework/Versions/Current/bin:$PATH"
		export ACLOCAL_FLAGS="-I /Library/Frameworks/Mono.framework/Versions/Current/share/aclocal"
	fi
	# add in libsvn's directory as a fallback path. user-set paths will override it
	export DYLD_FALLBACK_LIBRARY_PATH="$DYLD_FALLBACK_LIBRARY_PATH:/Library/Developer/CommandLineTools/usr/lib:/usr/local/lib:`pwd`/main/build/bin"

	ruby dependency_checker.rb || exit 1
fi

configure_packages
[ $? -eq 1 ] && exit 1

echo "PROFILE = $profile" > config.make
echo -n "SUBDIRS = " >> config.make

echo Configuration Summary
echo ---------------------
echo
echo "MonoDevelop has been configured with "
echo "    prefix = $prefix"
echo "    profile = $profile"
echo
echo "Packages included in the build:"
for p in $packages; do
	echo "\\" >> config.make
	echo -n "	$p" >> config.make
	echo "    $p"
done
echo >> config.make
echo

echo -n  "prefix=$prefix" >> config.make
